package com.mybatisflex.controller;

import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.entity.Account;
import com.mybatisflex.entity.core.Result;
import com.mybatisflex.entity.login.vo.LoginParamsVo;
import com.mybatisflex.service.IAccountService;
import com.mybatisflex.util.EncryptUtil;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/***
 * 登录相关接口
 */
@RestController
@RequestMapping()
public class LoginController {
    private final IAccountService accountService;

    public LoginController(IAccountService accountService) {
        this.accountService = accountService;
    }

    @RequestMapping("/login")
    public Result<SaTokenInfo> login(@RequestBody LoginParamsVo loginParamsVo) {
        Account account = accountService.getOne(new QueryWrapper().eq(Account::getAccountName, loginParamsVo.getAccountName()));
        if (ObjectUtils.isEmpty(account)) {
            return Result.fail("账号不存在!");
        }
        if (!(EncryptUtil.decrypt(account.getPassword()).equals(EncryptUtil.decrypt(loginParamsVo.getPassword())))) {
            return Result.fail("密码错误!");
        }
        StpUtil.login(account.getId());
        return Result.ok(StpUtil.getTokenInfo());
    }

    @RequestMapping("/logout")
    public Result<Integer> login() {
        StpUtil.logout();
        return Result.ok();
    }

}
